const express = require('express');
const path = require('path');
const app = express(); 
const bodyParser = require('body-parser');
app.all('*', (req, res, next) => {
 	res.header("Access-Control-Allow-Origin", "*");  
 	res.header('Access-Control-Allow-Credentials', true); 
 	res.header("Access-Control-Allow-Headers", "*");  
 	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");  
 	next();
 });
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use('/',express.static(__dirname + '/public'));//静态文件托管

const mysql = require("mysql2");
global.Pool = async (sqls, custom = {}) => {
	if(!sqls.length) return false
	
	let config = {
		host: 'localhost',
		user: 'root',
		port: '3306',
		password: '123456',
		database: 'n2_wow',
		...custom,
	}
	
	const pool_ = mysql.createPool(config);
	const isOnce = sqls.length  === 1;
	let res,result = [];
	
	let {err,conn} = await new Promise(r=> pool_.getConnection((err, conn) => r({err,conn})  ) )
	if (err) return false;
	
	err = await new Promise(r=> conn.beginTransaction( r))
	if (err) return false;
	
	for( const  {sql,params} of sqls){
		res = await  new Promise(r=>  conn.query(sql,params, (err, res, file) => r(err ? (console.log(err),false) : res)) );
		if( !res) {
			await new Promise(r=>  conn.rollback(r));  
			conn.destroy();	 
			return false;
		}
		if(isOnce) result =  res;
		else result.push(res);
	}
	//提交查询
	err = await new Promise( r=> conn.commit(r))
	if(err) return false;
	conn.destroy();
	
	return result;

};
module.exports = app;
